import { Module } from "vuex";
import { Howl } from "howler";
import { getOrderManageSetting } from "@/api/order";
import { getCommoditySet } from "@/api/commodity/commodity"

interface ISound {
  tenantId: string;
  createTime: string;
  updateTime: string;
  deleted: boolean;
  id: string;
  shopId: string;
  times: number;
  startTime: string;
  endTime: string;
  orderId: string;
  templateUrl: string;
  isOpen: number;
}

const module: Module<
  {
    sounds: ISound[];
    timer: any;
    setting: any;
    recover: any;
    isOpend: boolean;
  },
  any
> = {
  namespaced: true,
  state: {
    /** 播报列表 */
    sounds: [] as ISound[],
    /** 轮训定时器 */
    timer: null,
    /** 店铺设置 */
    setting: {},
    /** 回收设置 */
    recover: {},
    /** 播报是否打开 */
    isOpend: false,
  },
  getters: {
  },
  mutations: {
    
  },
  actions: {
    initSocket({ dispatch, state, rootState }) {
      const userInfo = rootState.user.userInfo;

      if (state.isOpend || !userInfo || !userInfo.shopInfoVo.shopId) return;

      dispatch("getShopSetting");
      dispatch("getShopInfo");

      // 打开一个 web socket
      const ws = new WebSocket(
        process.env.VUE_APP_WS + userInfo.shopInfoVo.shopId,
      );

      ws.onopen = function () {
        state.isOpend = true;
        setInterval(() => {
          ws.send("1");
        }, 9000);
      };

      ws.onmessage = function (evt) {
        const receivedMsg = JSON.parse(evt.data);
        if (receivedMsg && receivedMsg.mp3) {
          if (state.setting.orderNotify) {
            dispatch("handlePlay");
          }
        }
      };

      ws.onclose = function () {
        console.log("连接已关闭...");
      };
    },

    /** 获取店铺设置 */
    getShopSetting({ state }) {
      return getOrderManageSetting().then(res => {
        state.setting = res.data;
        return res.data;
      })
    },

    /** 获取回收设置 */
    getShopInfo({ state }) {
      return getCommoditySet({}).then(res => {
        state.recover = res.data;
        return res.data;
      })
    },

    /**
     * 处理播放
     */
    async handlePlay({ dispatch }) {
      try {
        await dispatch("playSound", {
          url: require("@/assets/order-reminder.mp3"),
        });
        return true;
      } catch (err) {
        return Promise.reject(false);
      }
    },

    /**
     * 播报声音
     */
    playSound(ctx, data: { url: string; id: string }) {
      return new Promise((resolve, reject) => {
        const howler = new Howl({
          src: [data.url],
        });

        let timer = null;

        howler.play();

        howler.on("play", () => {
          setTimeout(resolve, 2000);

          clearTimeout(timer);
        });

        timer = setTimeout(() => {
          reject("time out");
        }, 3000);

        howler.on("playerror", err => {
          reject(err);
        });

        howler.on("loaderror", err => {
          reject(err);
        });
      });
    },
  },
};

export default module;
